Several examples of how to write and use lambda expressions.
Press F5
This sample provides a brief introduction to the use of lambda expressions.
There are ten samples in this project. By default, the first sample will run. By changing the Main() method in Program.vb, you can modify the code to run one of the other samples. For instance, by default, Main makes the following call:
Samples.Sample1() |
Modify this code as follows to call Sample2():
Samples.Sample2() |
The samples are named Sample1(), Sample2(), and so forth, up to Sample10().

public static void Sample10() {
// use query expressions to simplify
var q = from p in persons
orderby p.Level, p.Name
group p.Name by p.Level into g
select new {Level = g.Key, Persons = g};
foreach(var g in q) {
Console.WriteLine("Level: {0}", g.Level);
foreach(var p in g.Persons) {
Console.WriteLine("Person: {0}", p);
}
}
}
public static void Sample10() { // use query expressions to simplify var q = from p in persons orderby p.Level, p.Name group p.Name by p.Level into g select new {Level = g.Key, Persons = g}; foreach(var g in q) { Console.WriteLine("Level: {0}", g.Level); foreach(var p in g.Persons) { Console.WriteLine("Person: {0}", p); } } }
Public Shared Sub Sample1()
' use Where() to filter out elements matching a particular condition
Dim fnums = numbers.Where(Function(n) n < 5)
Console.WriteLine("Numbers < 5")
For Each x As Integer In fnums
Console.WriteLine(x)
Next
End Sub
Public Shared Sub Sample2()
' use First() to find the one element matching a particular condition
Dim v As String = strings.First(Function(s) s(0) = "o"c)
Console.WriteLine("string starting with 'o': {0}", v)
End Sub
Public Shared Sub Sample3()
' use Select() to convert each element into a new value
Dim snums = numbers.Select(Function(n) strings(n))
Console.WriteLine("Numbers")
For Each s As String In snums
Console.WriteLine(s)
Next
End Sub
Public Shared Sub Sample1() ' use Where() to filter out elements matching a particular condition Dim fnums = numbers.Where(Function(n) n < 5) Console.WriteLine("Numbers < 5") For Each x As Integer In fnums Console.WriteLine(x) Next End Sub Public Shared Sub Sample2() ' use First() to find the one element matching a particular condition Dim v As String = strings.First(Function(s) s(0) = "o"c) Console.WriteLine("string starting with 'o': {0}", v) End Sub Public Shared Sub Sample3() ' use Select() to convert each element into a new value Dim snums = numbers.Select(Function(n) strings(n)) Console.WriteLine("Numbers") For Each s As String In snums Console.WriteLine(s) Next End Sub
For more information on LINQ: http://msdn.microsoft.com/en-us/netframework/aa904594.aspx